<template>
    
    <div>

        <van-nav-bar
  title="注册"
  left-text="返回"

  left-arrow
  @click-left="onClickLeft"

/>


        <van-form @submit="onSubmit">

         
 
  <van-cell-group inset>
    <van-field
      v-model="User.account"
      name="username"
      label="用户名"
      placeholder="用户名"
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
      <van-field
      v-model="User.phone"
      name="phone"
      label="手机号"
      placeholder="手机号"
      :rules="[{ required: true, message: '请填写手机号' }]"
    />
      
    <van-field
      v-model="User.password"
      type="password"
      name="password"
      label="密码"  
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
    <van-field
      v-model="User.password2"
      type="password"
      label="二次密码"  
      placeholder="请输入二次密码"
      :rules="passwordRule"
    />
  </van-cell-group>
   <!--上传头像 -->
          <van-uploader  v-model="fileHead" :after-read="afterRead" />
  <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit">
      提交
    </van-button>
  </div>
</van-form>
<div style="text-align: center;">已有账号？去
    <router-link to="/login">登录</router-link>
</div>
    </div>
</template>
<script setup>
import api from '@/api';
import { ref } from 'vue';
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter } from 'vue-router';
//定义路由对象
const router=useRouter()
const User=ref({})
//控制当前组件
const showCalendar =ref(false);
const fileHead=ref([])

   

//定义验证密码的数组
const passwordRule=[
    {required: true,message: '请填写密码'},
    {validator: (value)=>value===User.value.password,message: '两次密码不一致'}
]
const onClickLeft = () => history.back();
const formData=new FormData()
//当图片上传完 就会触发
const afterRead = (files) => {
      // 此时可以自行将文件上传至服务器
      console.log(files);
      //name=myHead 将上传的对象封装到formData中
      formData.append("myHead",files.file)
    };

//如果带文件上传功能  表单数据需要封装一个对象formDate
//发送请求时  需要设置请求头 multipart/form-data

//Elementplus官网提供的组件库
//自动封装文件对象，而且也需要设置请求头multipar/for
const onSubmit = (values) => {
    console.log('submit', values);
    //用于将values这个json对象数据  遍历出来
    //给上面的formData赋值
    Object.keys(values).forEach(key=>{
      formData.append(key,values[key])
    })
    api.postReq('/user/reg',formData,{
      headers:{
        'Content-Type':'multipart/form-data'
      }
    }).then(res=>{
      let result=res.data
      if(result.code==1){
        //提示
        showSuccessToast(result.msg);
        //跳转  需要引入useRouter组件 通过路由跳转
        router.push("/login")
      }else{
        showFailToast(result.msg);
      }
    })   
 };
</script>
<style scoped>

</style>
